'use strict'

const Service = require('egg').Service

class UserService extends Service {

    async login(param){
        const {app,ctx,service} = this;
        let rs = await ctx.model.FdUser.findOne({
            where:{
                username:param.username,
                deleted:'0',
                type:'0'
            }
        })
        if(!app.lodash.isEmpty(rs)){
            if(rs.forbidden == '1'){
                ctx.throw(401,'用户被禁用')
            }else{
                if (rs.password == await service.utils.md5(param.password)) {
                    let token =  await service.actionToken.apply(rs);
                    await this.setSession(token,rs.id)
                    return true;
                }else{
                    ctx.throw(401, '密码错误')
                }
            }
        }else{
            ctx.throw(404, '用户不存在')
        }
    }

    /**
     * 登录成功设置session
     * @returns {Promise<void>}
     */
    async setSession(token,id){
        const {app,ctx,service} = this;
        const ms = require('ms');
        const sequelize_query_param = {raw:true,type:app.Sequelize.QueryTypes.SELECT};
        let sql = `
        select a.*,b.code as rolename from fd_user a
        left join fd_role b on b.id = a.role_id
        where a.id = '${id}'
        `;
        let user = await ctx.model.query(sql,sequelize_query_param);
        let auth_sql = `
        select d.name,d.path,d.code from fd_user a
        left join fd_role_auth c on c.role_id = a.role_id
        left join fd_auth d on d.id = c.auth_id
        where a.id = '${id}'
        `;
        let auth = await ctx.model.query(auth_sql,sequelize_query_param);
        if(!app.lodash.isEmpty(auth)){
            user[0].auth = auth;
        }else{
            user[0].auth = [];
        }
        ctx.session.token = token;
        ctx.session.user_info = user[0];
        console.info(ctx.session.user_info)
        ctx.session.maxAge = ms('7d');
        return ;
    }


    /**
     * 更新密码service
     * @param param
     * @returns {Promise<boolean>}
     */
    async update(param){
        const {app,ctx,service} = this;
        //开启事务
        let t = await ctx.model.transaction();
        try {
            let user = await ctx.model.FdUser.findOne({where:{id:param.id,deleted: '0',password:await service.utils.md5(param.oldpassword)}})

            if(app.lodash.isEmpty(user)){
                return false;
            } else{
                user.password = await service.utils.md5(param.password);
                await user.save();

                //提交事务
                t.commit();

                //清空此模块的redis缓存
                app.sessionStore.destroy('admin_list');

                //删除此id的redis缓存
                app.sessionStore.destroy('admin_'+param.id);

                return true;
            }
        }catch (e) {
            //失败回滚
            t.rollback();
            //抛出错误信息
            ctx.throw(500,e.message)
        }
    }
}

module.exports = UserService
